//
//  ATDemoViewController.m
//  ATGaode_demo
//
//  Created by Chengquan Ye on 2019/3/4.
//  Copyright © 2019年 Chengquan Ye. All rights reserved.
//

#import "ATDemoViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <CoreMotion/CoreMotion.h>

#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>

#import "ATDemoTwoViewController.h"

#import "ATDrawTrackViewController.h"

#import <SVProgressHUD.h>
#import "RunLocationModel.h"

#import "ATMotionManager.h"

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define iPhone4S [UIScreen mainScreen].bounds.size.height == 480
#define iPhone5S [UIScreen mainScreen].bounds.size.height == 568
#define iPhone6S [UIScreen mainScreen].bounds.size.height == 667
#define iPhonePlus [UIScreen mainScreen].bounds.size.height == 736
#define iPad ([UIScreen mainScreen].bounds.size.height > 736 && [UIScreen mainScreen].bounds.size.height != 812)
#define iPhoneX ([UIScreen mainScreen].bounds.size.height == 812 && [UIScreen mainScreen].bounds.size.width == 375)
#define iPhoneXR [UIScreen mainScreen].bounds.size.height == 896
#define iPhoneXS_MAX [UIScreen mainScreen].bounds.size.height == 896
#define iPhoneX_series (iPhoneX || iPhoneXR || iPhoneXS_MAX)

#define NavHeight (iPhoneX_series ? 88 : 64)
#define TabBarHeight (iPhoneX_series ? 83 : 49)
#define SafeBottomHeight (iPhoneX_series ? 34 : 0)

@interface ATDemoViewController () <MAMapViewDelegate, AMapLocationManagerDelegate>
{
    // 走过的经纬度
    CLLocationCoordinate2D * _runningCoords;
    NSUInteger _count;
    MAMultiPolyline * _multiPolyline;
    MAPolyline * _polyline;
}

/** 高德地图view */
@property (nonatomic, strong) MAMapView *mapView;

/** 计算步数的对象 */
@property (strong, nonatomic) CMPedometer *pedonmeter;

///** 计算步数的另一个对象, 为了计算更新定位时是否走步了 */
//@property (strong, nonatomic) CMPedometer *otherPedonmeter;

/** 定位 */
@property (nonatomic, strong) AMapLocationManager *locationManager;

/** 经纬度 */
@property (nonatomic, strong) NSMutableArray *commonPolylineCoords;

/** 步数 */
@property (nonatomic, weak) UILabel *numberLbl;

/** 里程 */
@property (nonatomic, weak) UILabel *mileageLbl;
/** 速度 */
@property (nonatomic, weak) UILabel *speedLbl;


@property (nonatomic, strong) MAAnnotationView *userLocationAnnotationView;

//@property (nonatomic, strong) MAAnnotationView *endAnnotationView;

/** 最后一个大头针模型 */
@property (nonatomic, strong) MAPointAnnotation *endAnnotation;

//@property (nonatomic, strong) CLLocation *endLocation;

/** 开始记录 */
@property (nonatomic, assign) BOOL isRecording;
/** 结束记录 */
@property (nonatomic, assign) BOOL isEndRecording;

/** 结束时间 */
@property (nonatomic, strong) NSDate *endDate;

/** 定位更新的上一个时间 */
@property (nonatomic, strong) NSDate *lastUpdateDate;

/** 定位更新的当前时间 */
//@property (nonatomic, strong) NSDate *<#name#>;


/** <#name#> */
@property (nonatomic, strong) NSMutableArray *finishLocationArray;
/**  */
@property (nonatomic, assign) NSUInteger distance;
/** <#name#> */
@property (nonatomic, strong) RunLocationModel *endLocation;
/** <#name#> */
@property (nonatomic, assign) int endIndexPath;
/** <#name#> */
@property (nonatomic, strong) NSMutableArray *lineArray;
/** 纬度 */
@property (nonatomic, assign) double latitude;
/** 经度 */
@property (nonatomic, assign) double longitude;
/** <#name#> */
@property (nonatomic, strong) NSTimer *timer;


/** <#name#> */
@property (nonatomic, strong) NSMutableArray<MATraceLocation *> *points;
@property (nonatomic, strong) NSMutableArray *origOverlays; //处理前的
@property (nonatomic, strong) NSMutableArray *processedOverlays; //处理后的

/** <#name#> */
@property (nonatomic, strong) ATMotionManager *motionManager;

@end

@implementation ATDemoViewController

- (NSMutableArray<MATraceLocation *> *)points
{
    if (!_points) {
        _points = [NSMutableArray array];
    }
    return _points;
}

- (NSMutableArray *)origOverlays
{
    if (!_origOverlays) {
        _origOverlays = [NSMutableArray array];
    }
    return _origOverlays;
}

- (NSMutableArray *)processedOverlays
{
    if (!_processedOverlays) {
        _processedOverlays = [NSMutableArray array];
    }
    return _processedOverlays;
}

- (NSMutableArray *)finishLocationArray
{
    if (!_finishLocationArray) {
        _finishLocationArray = [NSMutableArray array];
    }
    return _finishLocationArray;
}

- (NSMutableArray *)lineArray
{
    if (!_lineArray) {
        _lineArray = [NSMutableArray array];
    }
    return _lineArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.commonPolylineCoords = [NSMutableArray array];
    
    self.pedonmeter = [[CMPedometer alloc] init];
//    self.otherPedonmeter = [[CMPedometer alloc] init];
    
    self.motionManager = [ATMotionManager manager];
    
    [self setupUI];
}

- (void)setupUI
{
    [self setupBottomView];
    
    // 创建地图
    [self setupMap];
    
}

- (void)setupBottomView
{
    UIView *bottomView = [[UIView alloc] init];
    bottomView.frame = CGRectMake(0, SCREEN_HEIGHT - 100 - SafeBottomHeight, SCREEN_WIDTH, 100);
    bottomView.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:bottomView];
    
    UILabel *numberLbl = [[UILabel alloc] init];
    numberLbl.frame = CGRectMake(20, 0, 300, 30);
    numberLbl.text = @"步数:0";
    [bottomView addSubview:numberLbl];
    self.numberLbl = numberLbl;
    
    UILabel *mileageLbl = [[UILabel alloc] init];
    mileageLbl.frame = CGRectMake(20, CGRectGetMaxY(numberLbl.frame), 300, 30);
    mileageLbl.text = @"里程:0";
    [bottomView addSubview:mileageLbl];
    self.mileageLbl = mileageLbl;
    
    UILabel *speedLbl = [[UILabel alloc] init];
    speedLbl.frame = CGRectMake(20, CGRectGetMaxY(mileageLbl.frame), 300, 30);
    speedLbl.text = @"速度:0";
    [bottomView addSubview:speedLbl];
    self.speedLbl = speedLbl;
}

- (void)setupRunNumber
{
    if ([CMPedometer isStepCountingAvailable]) {
        
        NSDate *endDate = [NSDate date];
        if (self.isEndRecording) {
            endDate = self.endDate;
        }
//        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//        [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
//        NSString *nowString = [formatter stringFromDate:nowDate];
//        NSLog(@"nowString = %@", nowString);
//        // 零点
//        NSString *zeroString = [nowString stringByReplacingCharactersInRange:NSMakeRange(nowString.length - 5, 5) withString:@"00:00"];
//        NSLog(@"zeroString = %@", zeroString);
//        NSDate *zeroDate = [formatter dateFromString:zeroString];
        [self.pedonmeter queryPedometerDataFromDate:self.startDate toDate:endDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
            if (error)
            {
                NSLog(@"请前往设置->隐私->运动与健身打开开关");
            }
            else {
                NSLog(@"步数===%@",pedometerData.numberOfSteps);
                NSLog(@"距离===%@",pedometerData.distance);
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.numberLbl.text = [NSString stringWithFormat:@"步数: %@", pedometerData.numberOfSteps];
                    self.mileageLbl.text = [NSString stringWithFormat:@"里程: %@", pedometerData.distance];
                });
            }
        }];
    }else{
        NSLog(@"计算步数不可用==");
    }
}

- (void)setupMap
{
    /*创建地图并添加到父view上*/
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, NavHeight, SCREEN_WIDTH, SCREEN_HEIGHT - NavHeight - 100 - SafeBottomHeight)];
    //    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    self.mapView.delegate = self;
    [self.view addSubview:self.mapView];
    
    ///如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
//    self.mapView.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
//    self.mapView.distanceFilter = 5; // kCLDistanceFilterNone
    
    self.mapView.pausesLocationUpdatesAutomatically = NO;
    
    // 不显示罗盘
    self.mapView.showsCompass = NO;
    
    // 不显示比例尺
    self.mapView.showsScale = NO;
    
    //是否自定义用户位置精度圈
    self.mapView.customizeUserLocationAccuracyCircleRepresentation = YES;
    MACircle *circle = [MACircle circleWithCenterCoordinate:self.mapView.userLocation.coordinate radius:0];
    [self.mapView addOverlay:circle];
    
    [self.mapView setZoomLevel:19];
    
//    [self.mapView setMaxZoomLevel:19];
    
    // 修改地图样式
    NSString *path = [NSString stringWithFormat:@"%@/style.data", [NSBundle mainBundle].bundlePath];
    NSData *styleData = [NSData dataWithContentsOfFile:path];
    MAMapCustomStyleOptions *styleOption = [[MAMapCustomStyleOptions alloc] init];
    styleOption.styleData = styleData;
    [self.mapView setCustomMapStyleOptions:styleOption];
    [self.mapView setCustomMapStyleEnabled:YES];
    
    //    CLLocationCoordinate2D currentCoor = CLLocationCoordinate2DMake(self.mapView.userLocation.location.coordinate.latitude, self.mapView.userLocation.location.coordinate.longitude);
    //    MACoordinateRegion region = MACoordinateRegionMake(currentCoor, MACoordinateSpanMake(100, 100));
    //    [self.mapView setRegion:region animated:YES];
    
    UIButton *startBtn = [[UIButton alloc] init];
    [startBtn setTitle:@"开始" forState:UIControlStateNormal];
    startBtn.frame = CGRectMake(SCREEN_WIDTH - 60 - 20, 120, 60, 40);
    startBtn.backgroundColor = [UIColor blackColor];
    [startBtn addTarget:self action:@selector(startBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:startBtn];
    
    
    UIButton *jumpBtn = [[UIButton alloc] init];
    [jumpBtn setTitle:@"jump" forState:UIControlStateNormal];
    jumpBtn.frame = CGRectMake(SCREEN_WIDTH - 60 - 20, CGRectGetMaxY(startBtn.frame) + 20, 60, 40);
    jumpBtn.backgroundColor = [UIColor blackColor];
    [jumpBtn addTarget:self action:@selector(jumpBtnClick) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:jumpBtn];
}

- (void)jumpBtnClick
{
    ATDemoTwoViewController *demoTwoVc = [[ATDemoTwoViewController alloc] init];
    [self.navigationController pushViewController:demoTwoVc animated:YES];
    
//    ATDrawTrackViewController *drawTrackVc = [[ATDrawTrackViewController alloc] init];
//    [self.navigationController pushViewController:drawTrackVc animated:YES];
}

//#pragma mark - 定时器相关
//- (void)addTimer
//{
//    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
//    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
//}
//
//- (void)timerAction
//{
//    [self changeLocation];
//}
//
//- (void)removeTimer
//{
//    [self.timer invalidate];
//    self.timer = nil;
//}

- (void)startBtnClick:(UIButton *)startBtn
{
    if ([startBtn.titleLabel.text isEqualToString:@"开始"]) {
        [startBtn setTitle:@"结束" forState:UIControlStateNormal];
        
        self.isRecording = YES;
        self.isEndRecording = NO;
        self.lastUpdateDate = [NSDate date];
        self.startDate = [NSDate date];
        
        [SVProgressHUD showSuccessWithStatus:@"开始l"];
        
        self.latitude = 25.434557;
        self.longitude = 119.037739;
        
        [self setupLocation];
        
        // 开始监听是否走步
        [self.motionManager startGyroUpdates];
        
//        [self.motionManager start:^(double accelerameter) {
//            NSLog(@"accelerameter === %f", accelerameter);
//        }];
        
//        [self addTimer];
        
//        [self setupRunNumber];
        
    } else {
//        [startBtn setTitle:@"开始" forState:UIControlStateNormal];
        self.endDate = [NSDate date];
        self.isRecording = NO;
        self.isEndRecording = YES;
        
//        [self removeTimer];
        // 结束持续定位
        [self.locationManager stopUpdatingLocation];
        
        [SVProgressHUD showSuccessWithStatus:@"结束"];
//        [self addEndAnnotation];
    }
}

#pragma mark - 添加最后一个大头针
- (void)addEndAnnotation
{
    if (self.endAnnotation) {
        return;
    }
    MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
//    annotation.coordinate = self.endLocation.coordinate;
    annotation.title    = @"AutoNavi";
    annotation.subtitle = @"CustomAnnotationView";
    [self.mapView addAnnotation:annotation];
    self.endAnnotation = annotation;
}

- (void)setupLocation
{
    // 定位
    self.locationManager = [[AMapLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.distanceFilter = kCLDistanceFilterNone; // 5
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; //kCLLocationAccuracyBestForNavigation; //kCLLocationAccuracyBest;
    
    //iOS 9（不包含iOS 9） 之前设置允许后台定位参数，保持不会被系统挂起
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    
    //iOS 9（包含iOS 9）之后新特性：将允许出现这种场景，同一app中多个locationmanager：一些只能在前台定位，另一些可在后台定位，并可随时禁止其后台定位。
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
        self.locationManager.allowsBackgroundLocationUpdates = YES;
    }
    //开始持续定位
    [self.locationManager startUpdatingLocation];
}

- (void)dealloc
{
    NSLog(@"demoVc ---- dealloc");
    if (_runningCoords)
    {
        free(_runningCoords);
        _count = 0;
    }
}

#pragma mark - MAMapViewDelegate
// 生成轨迹线段
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:overlay];
        
        polylineRenderer.lineWidth    = 5.f;
        polylineRenderer.strokeColor  = [UIColor colorWithRed:0 green:1 blue:0 alpha:1];
        polylineRenderer.lineJoinType = kCGLineJoinRound;
        polylineRenderer.lineCapType  = kCGLineCapRound;
        
        return polylineRenderer;
    }
    return nil;
}


// 添加大头针回调
//- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
//{
//    if ([annotation isKindOfClass:[MAPointAnnotation class]])
//    {
//        static NSString *customReuseIndetifier = @"customReuseIndetifier";
//
//        MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
//
//        if (annotationView == nil)
//        {
//            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
//            // must set to NO, so we can show the custom callout view.
//            annotationView.canShowCallout = NO;
//            annotationView.draggable = YES;
//            annotationView.calloutOffset = CGPointMake(0, -5);
//            annotationView.image = [UIImage imageNamed:@"dingwei_end"];
//        }
//
//        return annotationView;
//    }
//
//    return nil;
//}

//- (void)mapView:(MAMapView *)mapView didAddAnnotationViews:(NSArray *)views
//{
//    MAAnnotationView *view = views[0];
//
//    // 放到该方法中用以保证userlocation的annotationView已经添加到地图上了。
//    if ([view.annotation isKindOfClass:[MAUserLocation class]])
//    {
//        MAUserLocationRepresentation *pre = [[MAUserLocationRepresentation alloc] init];
////        pre.fillColor = [UIColor colorWithRed:0.9 green:0.1 blue:0.1 alpha:0.3];
////        pre.strokeColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.9 alpha:1.0];
//        pre.image = [UIImage imageNamed:@"dingwei"];
//        pre.lineWidth = 0;
//        pre.showsAccuracyRing = NO;
//        //        pre.lineDashPattern = @[@6, @3];
//
//        [self.mapView updateUserLocationRepresentation:pre];
//
//        view.calloutOffset = CGPointMake(0, 0);
//        view.canShowCallout = NO;
//        self.userLocationAnnotationView = view;
//    }
//}

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
//    NSLog(@"userLocation: 纬度: %f, 经度: %f", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
    if (updatingLocation) {
//        NSLog(@"userLocation == %f=---%f", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
        
//        if (self.isRecording) { // 开始记录时
//            [self drawTrack:userLocation.location];
//        }
    }
}

#pragma mark - AMapLocationManagerDelegate
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode
{
    NSLog(@"--location:{lat:%f; lon:%f}", location.coordinate.latitude, location.coordinate.longitude);
    
    

    if (self.isRecording) { // 开始记录时
//        RunLocationModel *locationModel = [[RunLocationModel alloc]init];
//        locationModel.location = location.coordinate;
//        locationModel.time = [NSDate date];
//        [self.finishLocationArray addObject:locationModel];
//
//        if (self.finishLocationArray.count > 1) {
//            RunLocationModel *lastButOneModel = self.finishLocationArray[self.finishLocationArray.count - 2];
//            [self distanceWithLocation:locationModel andLastButOneModel:lastButOneModel];
//        }
       
        [self drawTrack:location];
        
//        [self drawTrackCorrect:location];
    }
    
//    self.endLocation = location;
}

//计算距离,估算误差值
-(void)distanceWithLocation:(RunLocationModel *)lastModel andLastButOneModel:(RunLocationModel *)lastButOneModel{
    
    MAMapPoint point1 = MAMapPointForCoordinate(lastModel.location);
    MAMapPoint point2 = MAMapPointForCoordinate(lastButOneModel.location);
    
    //2.计算距离
    CLLocationDistance newdistance = MAMetersBetweenMapPoints(point1,point2);
    NSLog(@"newdistance === %f", newdistance);
    if (newdistance == 0) {
        [self.finishLocationArray removeObject:lastModel];
        return;
    }
    
    //估算两者之间的时间差,单位 秒
    NSTimeInterval secondsBetweenDates= [lastModel.time timeIntervalSinceDate:lastButOneModel.time];
    
    float speed = (float)newdistance/secondsBetweenDates;
    NSLog(@"速度: %f", speed);
    self.speedLbl.text = [NSString stringWithFormat:@"速度:%f", speed];
    //世界飞人9.97秒百米,当超过这个速度,即为误差值,可能是GPS不准
    if (speed < (float)100/9.74) {
    
        [self mapAddCommonPolyline2];//绘制运动轨迹
        self.distance  = self.distance +newdistance;
    }
}

-(void)mapAddCommonPolyline2 {
    
    NSMutableArray *tempArray = [self.finishLocationArray mutableCopy];
    
    RunLocationModel *lastlocation = tempArray[self.finishLocationArray.count - 1];
    RunLocationModel *lastLastlocation = tempArray[self.finishLocationArray.count - 2];
    MAMapPoint point1 = MAMapPointForCoordinate(lastlocation.location);
    MAMapPoint point2 = MAMapPointForCoordinate(lastLastlocation.location);
    
    //2.计算距离
    CLLocationDistance newDistance = MAMetersBetweenMapPoints(point1,point2);
    NSLog(@"newDistance == %f", newDistance);
    if (newDistance>5) {
        
        CLLocationCoordinate2D commonPolylineCoords[2];
        commonPolylineCoords[0] = lastlocation.location;
        commonPolylineCoords[1] = lastLastlocation.location;
        
        MAPolyline *commonPolyline = [MAPolyline polylineWithCoordinates:commonPolylineCoords count:2];
        
        [self.lineArray addObject:commonPolyline];
        [self.mapView addOverlay:commonPolyline];
    } else {
        [tempArray removeObject:lastlocation];
    }
    
    self.finishLocationArray = tempArray;
}

-(void)mapAddCommonPolyline{
    
    NSMutableArray *tempArray = [self.finishLocationArray mutableCopy];
    for (int i = _endIndexPath; i<tempArray.count; i++) {
        
        RunLocationModel *newlocation = tempArray[i];
        MAMapPoint point1 = MAMapPointForCoordinate(newlocation.location);
        MAMapPoint point2 = MAMapPointForCoordinate(_endLocation.location);
        
        //2.计算距离
        CLLocationDistance newDistance = MAMetersBetweenMapPoints(point1,point2);
        NSLog(@"newDistance == %f", newDistance);
        if (newDistance>10) {
            
            CLLocationCoordinate2D commonPolylineCoords[2];
            commonPolylineCoords[0] = newlocation.location;
            commonPolylineCoords[1] = self.endLocation.location;
            
            MAPolyline *commonPolyline = [MAPolyline polylineWithCoordinates:commonPolylineCoords count:2];
            
            [self.lineArray addObject:commonPolyline];
            [self.mapView addOverlay:commonPolyline];
            
            self.endIndexPath = i;
            self.endLocation = newlocation;
        } else {
            [tempArray removeObject:newlocation];
        }
    }
    
    self.finishLocationArray = tempArray;
}

//- (void)changeLocation
//{
//    self.latitude += 0.000115;
//    self.longitude += 0.000145;
//
//    RunLocationModel *locationModel = [[RunLocationModel alloc] init];
//    locationModel.location = CLLocationCoordinate2DMake(self.latitude, self.longitude);
//    [self.finishLocationArray addObject:locationModel];
//
//    if (self.finishLocationArray.count < 2) {
//        return;
//    }
//    self.endLocation = self.finishLocationArray[self.finishLocationArray.count - 2];
//    for (int i = _endIndexPath; i<self.finishLocationArray.count; i++) {
//
//        RunLocationModel *newlocation = self.finishLocationArray[i];
////        MAMapPoint point1 = MAMapPointForCoordinate(newlocation.location);
////        MAMapPoint point2 = MAMapPointForCoordinate(_endLocation.location);
//
//        //2.计算距离
////        CLLocationDistance newDistance = MAMetersBetweenMapPoints(point1,point2);
////        if (newDistance>10) {
//
//            CLLocationCoordinate2D commonPolylineCoords[2];
//            commonPolylineCoords[0] = newlocation.location;
//            commonPolylineCoords[1] = self.endLocation.location;
//
//            MAPolyline *commonPolyline = [MAPolyline polylineWithCoordinates:commonPolylineCoords count:2];
//
//            [self.lineArray addObject:commonPolyline];
//            [self.mapView addOverlay:commonPolyline];
//
//            self.endIndexPath = i;
////            self.endLocation = newlocation;
//
////        }
//    }
//}

/** 绘制轨迹 */
- (void)drawTrack:(CLLocation *)location
{
    NSMutableArray * indexes = [NSMutableArray array];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"latitude"] = @(location.coordinate.latitude);
    dict[@"longtitude"] = @(location.coordinate.longitude);
    [self.commonPolylineCoords addObject:dict];
    
    _count = self.commonPolylineCoords.count;
    _runningCoords = (CLLocationCoordinate2D *)malloc(_count * sizeof(CLLocationCoordinate2D));
    
    for (int i = 0; i < _count; i++)
    {
        @autoreleasepool
        {
            NSDictionary * data = self.commonPolylineCoords[i];
            _runningCoords[i].latitude = [data[@"latitude"] doubleValue];
            _runningCoords[i].longitude = [data[@"longtitude"] doubleValue];
            
            [indexes addObject:@(i)];
        }
    }
    
    
//    _multiPolyline = [MAMultiPolyline polylineWithCoordinates:_runningCoords count:_count drawStyleIndexes:indexes];
    
    [self.mapView removeOverlays:self.mapView.overlays];
    _polyline = [MAPolyline polylineWithCoordinates:_runningCoords count:_count];
        
    //在地图上添加折线对象
    [self.mapView addOverlay:_polyline];
    
    [self setupRunNumber];
}

// 轨迹纠偏划线
- (void)drawTrackCorrect:(CLLocation *)location
{
    MATraceLocation *traceLoc = [[MATraceLocation alloc] init];
    traceLoc.loc = location.coordinate;
    [self.points addObject:traceLoc];
    
    NSLog(@"原来的点个数=======%zd", self.points.count);
    
    MATraceManager *temp = [[MATraceManager alloc] init];
    [temp queryProcessedTraceWith:self.points type:AMapCoordinateTypeAMap processingCallback:^(int index, NSArray<MATracePoint *> *points) {
        NSLog(@"纠偏后进度=======%zd", points.count);
    } finishCallback:^(NSArray<MATracePoint *> *points, double distance) {
        NSLog(@"纠偏后个数=======%zd", points.count);
        [self addFullTrace:points toMapView:self.mapView];
    } failedCallback:^(int errorCode, NSString *errorDesc) {
        
    }];
    
}

- (void)addFullTrace:(NSArray<MATracePoint*> *)tracePoints toMapView:(MAMapView *)mapView{
    MAMultiPolyline *polyline = [self makePolyLineWith:tracePoints];
    if(!polyline) {
        return;
    }
    [mapView removeOverlays:self.processedOverlays];
    [self.processedOverlays removeAllObjects];

    [self.processedOverlays addObject:polyline];
    [mapView addOverlays:self.processedOverlays];
}

- (MAMultiPolyline *)makePolyLineWith:(NSArray<MATracePoint*> *)tracePoints {
    if(tracePoints.count == 0) {
        return nil;
    }
    
    CLLocationCoordinate2D *pCoords = malloc(sizeof(CLLocationCoordinate2D) * tracePoints.count);
    if(!pCoords) {
        return nil;
    }
    
    for(int i = 0; i < tracePoints.count; ++i) {
        MATracePoint *p = [tracePoints objectAtIndex:i];
        CLLocationCoordinate2D *pCur = pCoords + i;
        pCur->latitude = p.latitude;
        pCur->longitude = p.longitude;
    }
    
    MAMultiPolyline *polyline = [MAMultiPolyline polylineWithCoordinates:pCoords count:tracePoints.count];
    
    if(pCoords) {
        free(pCoords);
    }
    
    return polyline;
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
//    // 返回删除定时器
//    if (self.navigationController.topViewController == nil) {
//        [self removeTimer];
//    }
}

@end
